<?php

namespace common\models\info;

use backend\component\ResultFormat;
use common\component\BaseActiveRecord;
use common\component\CacheHelper;
use common\component\Constant;
use common\models\base\AttachmentService;
use common\utils\CommonUtil;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\Url;

/**
 * This is the model class for table "{{%zt_tags}}".
 *
 * @property string $id
 * @property string $tag_name 标签名称
 * @property int $article_total 文章总数
 * @property string $desc 描述
 * @property int $status 状态
 * @property string $updated_at 更新时间
 * @property string $created_at 创建时间
 */
class Tags extends BaseActiveRecord
{
    const STATUS_ENABLE = 1;   //启用
    const STATUS_DISABLE = 0;  //禁用

    const REC_NORMAL = 0; //正常
    const REC_HOT = 1; //热门话题
    const REC_RECOMMEND = 2; //推荐
    const REC_All = 3; //热门话题,推荐

    const TOTAL_ARTICLE = "article_total";

    const ADD = "+";
    const REDUCE = "-";
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%zt_tags}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [[ 'article_total','status', 'updated_at', 'created_at'], 'integer'],
            [['desc'], 'string'],
            [['tag_name'], 'string', 'max' => 32],
            ['tag_name','trim']

        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => '序列',
            'tag_name' => '标签名',
            'article_total' => '关联文章',
            'desc' => '描述',
            'status' => '状态',
            'updated_at' => '更新时间',
            'created_at' => '创建时间',
        ];
    }

    public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::className(),
                'attributes' => [
                    self::EVENT_BEFORE_INSERT => ['created_at'],
                    self::EVENT_BEFORE_UPDATE => ['updated_at']
                ]
            ]
        ];
    }


    static $statusArr = [
        self::STATUS_DISABLE => '禁止',
        self::STATUS_ENABLE => '启用',
    ];



    /**
     * 保存数据之前
     * @param bool $insert
     * @return bool
     */
    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }
        if ($insert) {
            $this->updated_at = $this->created_at;
            //检查是否存在
            if (static::find()->where(['tag_name'=>$this->tag_name])->exists()) {
                $this->addError("tag_name","【".$this->tag_name."】已存在");
                return false;
            }
        } else {
            $where_one = ['and'];
            $where_one[] = ['=','tag_name',$this->tag_name];
            $where_one[] = ['!=','id',$this->id];
            if (static::find()->where($where_one)->exists()) {
                $this->addError("tag_name","【".$this->tag_name."】已存在");
                return false;
            }
        }
        return true;
    }


    public function afterFind()
    {
        parent::afterFind();
        $this->ui();
    }

    public function ui() {
        $this->ui['status'] = self::$statusArr[$this->status];
        $this->ui['desc'] = $this->desc ? "是" : "否";
        $this->ui["created_at"] = date("Y-m-d H:i:s",$this->created_at);
        $this->ui["updated_at"] = date("Y-m-d H:i:s",$this->updated_at);
        $this->ui['article_total'] = "<a href='".Url::to(['/info/tag/artotal','tag_id'=>$this->id])."'>".$this->article_total."</a>";
    }



    /**
     * 字段自增或自减
     */
    public static function fieldIncrAndReduc($id,$field=self::TOTAL_ARTICLE,$operater = self::ADD) {
        $model = static::findOne($id);
        if (!$model) return false;
        //如果<=0 则跳过
        if (!($model->$field > 0)) return false;
        return $model->updateCounters([$field=>$operater."1"]);
    }

    public function dataListTable($post) {
        //请求参数组装
        $where = ["and"];

        if (!empty($post['tag_name'])) {
            $where[] = ['like','tag_name',trim($post['tag_name'])];
        }
        $query = self::find()->where($where);
        $dataArr = self::table($query,$post);
        return $dataArr;
    }

    /**
     * 实例化模型对像
     * @param $id
     * @return BaseActiveRecord|null|static
     */
    public static function modelById($id) {
        if (!$id) {
            $model = new self();
        }
        else {
            $model = static::findOne($id);
        }
        return $model;
    }

    /**
     * 获取新创建的tag
     * @param $time
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function getTagsYesterday($time) {
        $data =[];
        if (!$data) {
            $where = ['and'];
            $where[] = ['=','status',self::STATUS_ENABLE];
            $where[] = ['>','updated_at',$time];
            $data = static::find()->select("id,tag_name")
                ->where($where)
                ->asArray()
                ->all();
        }
        return $data;
    }

    /**
     * 获取字段
     * @param $id
     * @param string $field
     * @return string
     */
    public static function getFieldById($id,$field="tag_name") {
        $data = self::loadRowData($id);
        return isset($data[$field]) ? $data[$field] : "";
    }


    public static function loadRowData($id) {
            $data = static::find()->where(['id'=>$id])->asArray()->one();
        return $data;
    }


    public static function loadRowDataByName($tag_name) {
            $data = static::find()->select("id,tag_name,article_total,desc")->where(['tag_name'=>$tag_name,"status"=>self::STATUS_ENABLE])->asArray()->one();
        return $data;
    }


    public static function loadRowDataById($tag_id) {
            $data = static::find()->select("id,tag_name,article_total,desc")->where(['id'=>$tag_id,"status"=>self::STATUS_ENABLE])->asArray()->one();
        return $data;
    }


    /**
     * 添加文章时增加的标签
     * id > 0  代表已存在
     * id == 0  需要添加的标签
     * @param $artId  文章id
     * @param $tagsArr 标签数组
     * @param $status
     * @param $changeAttribute
     * @return array
     */
    public static function refreshTagsByArticle($artId,$tagsArr,$status,$changeAttribute) {
        //标签数组中有值检查是否有未添加的
        $tagIds = [];
        if (count($tagsArr)) {
            foreach ($tagsArr as $item) {
                //新标签
                //新标签
                if ($item['id']=='') {
                    $model = static::find()->where(["tag_name"=>trim($item['text'])])->one();
                    if (!$model) {
                        $model = new self();
                        $model->tag_name = trim($item['text']);
                    }
                } else { //已存在的标签
                    $model = static::modelById($item['id']);
                    if (!$model) {
                        continue;
                    }
                }
                //审核通过
                if (isset($changeAttribute['status']) && ($changeAttribute['status'] != Article::STATUS_PASS && $status == Article::STATUS_PASS)) {
                    $model->article_total += 1;
                }
                //如果审核通过改为其它状态
                if (isset($changeAttribute['status']) && ($changeAttribute['status'] == Article::STATUS_PASS && $status != Article::STATUS_PASS)) {
                    $model->article_total = $model->article_total > 0 ? $model->article_total - 1 : 0;
                }
                $model->status = self::STATUS_ENABLE;
                if (!$model->save()) {
                    Yii::error($model->getErrorsToString());
                    continue;
                }
                $tagIds[] = $model->id;
            }
        }
        // 存入标签关系表中
        $dbTagIds = TagsRelation::arrTagIdsList($artId);
        $addTags = array_diff($tagIds,$dbTagIds);
        $reduceTags = array_diff($dbTagIds,$tagIds);
        if ($addTags) {
            TagsRelation::addTags($artId,$addTags);
        }
        if ($reduceTags) {
            TagsRelation::reduceTags($artId,$reduceTags);
        }
        return TagsRelation::arrTagIdsList($artId);
    }

    public static function arrHotTag($num=3) {
            $data = static::find()->select("id,tag_name,status,desc")
                    ->where(["status"=>self::STATUS_ENABLE])
                    ->orderBy("id DESC")
                    ->asArray()
                    ->limit($num)
                    ->all();
            if (count($data)>0) {
                foreach ($data as $k => $row) {
                    $data[$k] = $row;
                    $data[$k]['hot_tag_url'] = CommonUtil::generateUrl($row['id'], Constant::ROUTE_TAG);    //热门话题url
                }
            }
        return $data;
    }

    public static function arrIndexHotTag($is_rec = self::REC_HOT,$page=1,$pageSize=9) {
            $q = static::find()->select("id,tag_name,status")->where(["status"=>self::STATUS_ENABLE])->andWhere("is_rec=is_rec|$is_rec")->orderBy("id DESC");
            $data = self::arrListByPage($q,$page,$pageSize);
            if (count($data["rows"])) {
                foreach ($data["rows"] as $k => $row) {
                    foreach ($row as $kk => $vv) {
                        if (is_null($vv)) {
                            unset($data["rows"][$k][$kk]);
                        } else {
                            $data['rows'][$k]['hot_tag_url'] = CommonUtil::generateUrl($row['id'], Constant::ROUTE_TAG);    //热门话题url
                        }

                    }
                }
        }
        return $data;
    }

    public function getRecComboList() {
        $result = [
            ["id"=>-1,"text"=>"请选择状态"],
            ["id"=>self::REC_NORMAL,"text"=>"正常"],
            ['id'=>self::REC_HOT,"text"=>"热门话题"],
            ['id'=>self::REC_RECOMMEND,"text"=>"推荐"],
            ['id'=>self::REC_All,"text"=>"热门话题+推荐"]
        ];
        return $result;
    }
   public static function getAllTag(){
       $key = "tags:select";
       $data = CommonUtil::getCache(__CLASS__,$key);
       if(!$data){
           $data = static::find()->select("id,tag_name,status,article_total")->where(["status"=>self::STATUS_ENABLE])
                   ->orderBy("article_total DESC")
                    ->limit(18)
                   ->asArray()
                   ->all();
           if (count($data)>0) {
               foreach ($data as $k => $row) {
                   $data[$k] = $row;
                   $data[$k]['tag_url'] = CommonUtil::generateUrl($row['id'], Constant::ROUTE_TAG);    //热门话题url
               }
           }
           CommonUtil::setCache(__CLASS__,$key,$data,3600);
       }
       return $data;
   }
   public static function getAllTags(){
       $key = "tags:all";
       $data = CommonUtil::getCache(__CLASS__,$key);
       if(!$data){
           $data = static::find()->select("id,tag_name,status,article_total")->where(["status"=>self::STATUS_ENABLE])
               ->orderBy("article_total DESC")
               ->asArray()
               ->all();
           if (count($data)>0) {
               foreach ($data as $k => $row) {
                   $data[$k] = $row;
                   $data[$k]['tag_url'] = CommonUtil::generateUrl($row['id'], Constant::ROUTE_TAG);    //热门话题url
               }
           }
           CommonUtil::setCache(__CLASS__,$key,$data,3600);
       }
       return $data;
   }
}
